<?php

namespace Plugins\WebSite\Http;

use App\Exception\ApiMessageException;
use App\Util\Helper;
use Hyperf\Di\Annotation\Inject;
use Psr\SimpleCache\CacheInterface;
use Sc\Util\ScTool;

class PageInfo
{
    private string $infoPath = __DIR__ . '/page_info';

    private int $latestTime = 0;

    private array $pageList = [];

    private string $indexPage = 'index';


    public static function init()
    {
        $pageInfo = Helper::getContainer(PageInfo::class);
        $pageList = $pageInfo->getPageList();
        $glob = glob(BASE_PATH . '/plugins/WebSite/Pages/*.php');
        foreach ($glob as $dir) {
            $page = strtr(strtr(strtr($dir, [BASE_PATH . '/plugins/WebSite/Pages/' => '']), ['/' => '.']), ['.php' => '']);
            if (empty($pageInfo->pageList[$page])) {
                $pageInfo->pageList[$page] = [
                    'page' => $page,
                    'title' => $page,
                    'enable' => 1,
                ];
            }
            if (!empty($pageInfo->pageList[$page]['isIndex'])) {
                $pageInfo->indexPage = $page;
                $pageInfo->pageList[$page]['isIndex'] = 1;
            }else if($pageInfo->indexPage == 'index' && $page == 'index'){
                $pageInfo->pageList[$page]['isIndex'] = 1;
            }else{
                $pageInfo->pageList[$page]['isIndex'] = 0;
            }
        }

        file_put_contents($pageInfo->infoPath, json_encode($pageInfo->pageList));
    }

    /**
     * @param string $page
     * @return mixed|null|array{page:"",title:"",enable:0}
     */
    public function getPage(string $page): mixed
    {
        $this->getPageList();

        return $this->pageList[$page] ?? null;
    }

    public function getPageList(): array
    {
        if ($this->latestTime + 60 < time()) {
            $this->pageList = json_decode(file_get_contents($this->infoPath), true) ?: [];
        }
        return array_values($this->pageList);
    }

    public function setPage(string $page, array $pageInfo): void
    {
        $pageList = json_decode(file_get_contents($this->infoPath), true) ?: [];
        if (isset($pageList[$page])) {
            throw new ApiMessageException('页面已存在');
        }
        $pageList[$page] = $pageInfo;
        file_put_contents($this->infoPath, json_encode($pageList));
        $this->pageList = $pageList;
        $this->latestTime = time();
    }

    public function getCode(string $page): bool|string
    {
        $pagesDir = BASE_PATH . '/plugins/WebSite/Pages';
        $file = $pagesDir . '/' . $page . '.php';
        return file_exists($file) ? file_get_contents($file) : '';
    }

    public function setCode(string $page, string $code): void
    {
        $pagesDir = BASE_PATH . '/plugins/WebSite/Pages';
        $file = $pagesDir . '/' . $page . '.php';
        file_put_contents($file, $code);
    }
}